package com.guli.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guli.eduservice.bean.EduSubject;
import com.guli.eduservice.bean.Excel.SubjectData;
import com.guli.eduservice.service.EduSubjectService;
import com.guli.servicebase.exceptionHandler.GuliException;

import java.util.Map;

/**
 * @ClassName SubjectExcelListener
 * @Description TODO
 * @Author YinLiangTao Email:1517535831@qq.com
 * @Date 2022/4/2 20:53
 * @Version 1.0
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    private EduSubjectService eduSubjectService;
    public SubjectExcelListener(){}
    public SubjectExcelListener(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }
    //一行一行读取数据到数据库
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }
        //读取一级分类和二级分类
        //判断一级分类是否重复
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if(existOneSubject == null){
            existOneSubject = new EduSubject();
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            existOneSubject.setParentId("0");
            eduSubjectService.save(existOneSubject);
        }
        //判断二级分类是否重复
        String pid = existOneSubject.getId();
        EduSubject existSecondSubject = this.existSecondSubject(eduSubjectService, subjectData.getSecondSubjectName(),pid);
        if(existSecondSubject == null){
            existSecondSubject = new EduSubject();
            existSecondSubject.setTitle(subjectData.getSecondSubjectName());
            existSecondSubject.setParentId(pid);
            eduSubjectService.save(existSecondSubject);
        }
    }
    //判断一级分类不能重复添加
    public EduSubject existOneSubject(EduSubjectService eduSubjectService,String name)
    {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<EduSubject>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject one = eduSubjectService.getOne(wrapper);
        return one;
    }

    //判断二级分类不能重复添加
    public EduSubject existSecondSubject(EduSubjectService subjectService,String name,String pid)
    {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<EduSubject>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
